package org.tulkas.l10n;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractMessageSource;
import org.tulkas.base.Constants;
import org.tulkas.base.ITulkasApplicationContext;
import org.tulkas.util.FileUtil;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
public class TulkasMessageSource extends AbstractMessageSource {
	private static Logger logger = LoggerFactory
			.getLogger(TulkasMessageSource.class);

	private final Map<Locale, Map<String, MessageFormat>> cachedMsgFormats = new HashMap<Locale, Map<String, MessageFormat>>();

	@Autowired
	private ITulkasApplicationContext applicatoinContext = null;

	private ResourceBundleControl resourceControl = null;

	/* (non-Javadoc)
	 * @see org.springframework.context.support.AbstractMessageSource#resolveCode(java.lang.String, java.util.Locale)
	 */
	@Override
	protected MessageFormat resolveCode(String code, Locale locale) {
		synchronized (cachedMsgFormats) {
			Map<String, MessageFormat> map = cachedMsgFormats.get(locale);
			if (map != null) {
				MessageFormat mf = map.get(code);
				if (mf != null) {
					return mf;
				}
			} else {
				map = new HashMap<String, MessageFormat>();
				cachedMsgFormats.put(locale, map);
			}

			ResourceBundle rb = ResourceBundle.getBundle(
					Constants.L10N_BASE_NAME, locale, applicatoinContext
							.getClass().getClassLoader(), resourceControl);
			String msg = rb.getString(code);
			if (msg != null) {
				MessageFormat mf = createMessageFormat(msg, locale);
				map.put(code, mf);
				return mf;
			} else {
				return null;
			}
		}
	}

	@Override
	protected String resolveCodeWithoutArguments(String code, Locale locale) {
		ResourceBundle rb = ResourceBundle.getBundle(Constants.L10N_BASE_NAME,
				locale, ITulkasApplicationContext.class.getClassLoader(),
				resourceControl);
		return rb.getString(code);
	}

	public void init() {
		logger.info("Initializing Tulkas localization message source");
		resourceControl = new ResourceBundleControl(FileUtil
				.trimFilePath(applicatoinContext.getRootPath()));
	}
}
